package com.yfyszk.kingbird.controller;

import com.github.pagehelper.PageInfo;
import com.yfyszk.kingbird.document.Book;
import com.yfyszk.kingbird.page.Page;
import com.yfyszk.kingbird.service.impl.EsService;
import com.yfyszk.kingbird.service.impl.EsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping(value = "/es")
@RestController
public class ElasticSaveController {
    @Autowired
    private EsService bookService;
    /**
     * 新增 / 修改索引
     * @return
     */
    @RequestMapping("save")
    public String add(Book Book) {
        IndexResponse putOne = bookService.putOne(new Book(1, "wgc"));
        System.out.println("【1】putOne：" + putOne);
        return "success";
    }

    /**
     * 删除索引
     * @return
     */
    @RequestMapping("delete/{id}")
    public String delete(@PathVariable String id) {
        
        return "success";
    }
    /**
     * 清空索引
     * @return
     */
    @RequestMapping("delete_all")
    public String deleteAll(@PathVariable String id) {
       
        return "success";
    }

    /**
     * 根据ID获取
     * @return
     */
    @RequestMapping("get/{id}")
    public Book getById(@PathVariable int id){
        Book book = bookService.getByBookId(id);
        return book;
    }

    /**
     * 根据获取全部
     * @return
     */
    @RequestMapping("get_all")
    public List<Book> getAll(){
        return null;
    }

    /**
     * 搜索
     * @param keyword
     * @return
     */
    @RequestMapping("query")
    public List<Book> query(String keyword){
        return bookService.getAll();
    }

    /**
     * 搜索，命中关键字高亮
     * http://localhost:8080/query_hit?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc
     * @param keyword   关键字
     * @param indexName 索引库名称
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @RequestMapping("query_hit")
    public List<Map<String,Object>> queryHit(@RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields){
        String[] fieldNames = {};
        if(fields.contains(",")) fieldNames = fields.split(",");
        else fieldNames[0] = fields;
        return null;
    }

    /**
     * 搜索，命中关键字高亮
     * http://localhost:8080/query_hit_page?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc&pageNo=1&pageSize=1
     * @param pageNo    当前页
     * @param pageSize  每页显示的数据条数
     * @param keyword   关键字
     * @param indexName 索引库名称
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @RequestMapping("query_hit_page")
    public Page<Map<String,Object>> queryHitByPage(int pageNo, int pageSize
            , String keyword, String indexName, String fields){
        String[] fieldNames = {};
        if(fields.contains(",")) fieldNames = fields.split(",");
        else fieldNames[0] = fields;
        return null;
    }
    @RequestMapping("queryAll_page")
    public Page<Map<String,Object>> queryAllPage(  int pageNo, int pageSize,String indexName){

        return null;
    }

    /**
     * 删除索引库
     * @param indexName
     * @return
     */
    @RequestMapping("delete_index")
    public String deleteIndex(String indexName){

        return "success";
    }
    @RequestMapping("addBatch")
    public String addBatch(){
        List<Book> list = new ArrayList<>();
        list.add(new  Book(2, "水浒传"));
        list.add(new  Book(3, "三国演义"));
        BulkResponse putBatch = bookService.putBatch(list);
        System.out.println("【2】putBatch：" + putBatch.status());
        return "ok";
    }





    @RequestMapping("pageComprehensiveQuery")
    public PageInfo<Book> pageComprehensiveQuery(Book book) throws Exception {
        SearchSourceBuilder searchSourceBuilder = getSearchSourceBuilder(book);
        PageInfo page = bookService.searchByPage(searchSourceBuilder,book.getPageNum(), book.getPageSize(), book);
        // 转换
        List<Book> list = page.getList();
        page.setList(list);
        return page;
    }


    /**
     * 拼接综合查询 查询条件
     * @param book
     * @return
     */
    private SearchSourceBuilder getSearchSourceBuilder(Book book){
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        if (book.getPageNum() == null) {
            book.setPageNum(1);
        }

        if (book.getPageSize() == null) {
            book.setPageSize(10000);
        }

        sourceBuilder.from((book.getPageNum()-1)*book.getPageSize());
        sourceBuilder.size(book.getPageSize());

        // 上报时间拼接时/分/秒
        if (!ObjectUtils.isEmpty(book.getName())) {
            book.setName(book.getName());
        }
      /*  if (!ObjectUtils.isEmpty(comprehensiveQueryEventVO.getReportEndTime())) {
            comprehensiveQueryEventVO.setReportEndTime(comprehensiveQueryEventVO.getReportEndTime() + " 23:59:59");
        }
        // 截止时间拼接时/分/秒
        if (!ObjectUtils.isEmpty(comprehensiveQueryEventVO.getDeadLineStartTime())) {
            comprehensiveQueryEventVO.setDeadLineStartTime(comprehensiveQueryEventVO.getDeadLineStartTime() + " 00:00:00");
        }
        if (!ObjectUtils.isEmpty(comprehensiveQueryEventVO.getDeadLineEndTime())) {
            comprehensiveQueryEventVO.setDeadLineEndTime(comprehensiveQueryEventVO.getDeadLineEndTime() + " 23:59:59");
        }
*/
        // 符合条件查询
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();

        // event_state_id != 0 and event_state_id != 11 and delete_flag != 1
        boolBuilder.mustNot(QueryBuilders.termQuery("eventStateId", 0));
        boolBuilder.mustNot(QueryBuilders.termQuery("eventStateId", 11));
        boolBuilder.mustNot(QueryBuilders.termQuery("delateFlag", 1));

        // 动态条件----keyword
        if (StringUtils.isNotEmpty(book.getName())) {
            boolBuilder.must(QueryBuilders.queryStringQuery(book.getName()));
        }

        /*// 拼接动态查询条件
        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getEventCode())) {
            boolBuilder.must(QueryBuilders.termQuery("eventCode", comprehensiveQueryEventVO.getEventCode()));
        }

        if (comprehensiveQueryEventVO.getEventGradeId() != null) {
            boolBuilder.must(QueryBuilders.termQuery("eventGradeId", comprehensiveQueryEventVO.getEventGradeId()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getEventGradeName())) {
            boolBuilder.must(QueryBuilders.termQuery("eventGradeNam", comprehensiveQueryEventVO.getEventGradeName()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getEventTypeName())) {
            boolBuilder.must(QueryBuilders.termQuery("eventTypeName", comprehensiveQueryEventVO.getEventTypeName()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getEventTypeCode())) {
            boolBuilder.must(QueryBuilders.termQuery("eventTypeCode", comprehensiveQueryEventVO.getEventTypeCode()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getEventSubtypeName())) {
            boolBuilder.must(QueryBuilders.termQuery("eventSubtypeName", comprehensiveQueryEventVO.getEventSubtypeName()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getEventSubtypeCode())) {
            boolBuilder.must(QueryBuilders.termQuery("eventSubtypeCode", comprehensiveQueryEventVO.getEventSubtypeCode()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getAreaRegionName())) {
            boolBuilder.must(QueryBuilders.termQuery("areaRegionName", comprehensiveQueryEventVO.getAreaRegionName()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getAreaRegionCode())) {
            boolBuilder.must(QueryBuilders.termQuery("areaRegionCode", comprehensiveQueryEventVO.getAreaRegionCode()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getCommRegionName())) {
            boolBuilder.must(QueryBuilders.termQuery("commRegionName", comprehensiveQueryEventVO.getCommRegionName()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getCommRegionCode())) {
            boolBuilder.must(QueryBuilders.termQuery("commRegionCode", comprehensiveQueryEventVO.getCommRegionCode()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getStreetRegionName())) {
            boolBuilder.must(QueryBuilders.termQuery("streetRegionName", comprehensiveQueryEventVO.getStreetRegionName()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getStreetRegionCode())) {
            boolBuilder.must(QueryBuilders.termQuery("streetRegionCode", comprehensiveQueryEventVO.getStreetRegionName()));
        }

        if (comprehensiveQueryEventVO.getEventSrcId() != null) {
            boolBuilder.must(QueryBuilders.termQuery("eventSrcId", comprehensiveQueryEventVO.getEventSrcId()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getEventSrcName())) {
            boolBuilder.must(QueryBuilders.termQuery("eventSrcName", comprehensiveQueryEventVO.getEventSrcName()));
        }

        if (comprehensiveQueryEventVO.getProcTimeStateId() != null) {
            boolBuilder.must(QueryBuilders.termQuery("procTimeStateId", comprehensiveQueryEventVO.getProcTimeStateId()));
        }

        if (comprehensiveQueryEventVO.getPressFlag() != null) {
            boolBuilder.must(QueryBuilders.termQuery("pressFlag", comprehensiveQueryEventVO.getPressFlag()));
        }

        if (comprehensiveQueryEventVO.getOverseerFlag() != null) {
            boolBuilder.must(QueryBuilders.termQuery("overseerFlag", comprehensiveQueryEventVO.getOverseerFlag()));
        }

        if (comprehensiveQueryEventVO.getEventStateId() != null) {
            boolBuilder.must(QueryBuilders.termQuery("eventStateId", comprehensiveQueryEventVO.getEventStateId()));
        }

        if (comprehensiveQueryEventVO.getActTimeStateId() != null) {
            boolBuilder.must(QueryBuilders.termQuery("act.actTimeStateId", comprehensiveQueryEventVO.getActTimeStateId()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getReportStartTime())) {
            boolBuilder.must(QueryBuilders.rangeQuery("procStartTime").gte(comprehensiveQueryEventVO.getReportStartTime()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getReportEndTime())) {
            boolBuilder.must(QueryBuilders.rangeQuery("procStartTime").lte(comprehensiveQueryEventVO.getReportEndTime()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getDeadLineStartTime())) {
            boolBuilder.must(QueryBuilders.rangeQuery("act.deadLine").gte(comprehensiveQueryEventVO.getDeadLineStartTime()));
        }

        if (StringUtils.isNotEmpty(comprehensiveQueryEventVO.getDeadLineEndTime())) {
            boolBuilder.must(QueryBuilders.rangeQuery("act.deadLine").lte(comprehensiveQueryEventVO.getDeadLineEndTime()));
        }*/
        sourceBuilder.query(boolBuilder);
        return sourceBuilder;
    }
}
